import axios from 'axios'
// 创建axios实例对象
import store from '@/store'

import router from '@/router'
import to from 'await-to-js'

import { refreshTokenAPI } from '@/api/user'

const instance = axios.create({
  baseURL: 'http://101.35.25.8:8000/v1_0/',

  timeout: 6000 // 超时时间，超时时间最好给够，或者时间段多去请求
})

// 每次请求都可以拦截到
instance.interceptors.request.use(config => {
  // console.log('请求拦截')
  // vuex记录cancelToken
  config.cancelToken = new axios.CancelToken((cancel) => {
    store.commit('user/pushToken', {
      cancelToken: cancel
    })
  })
  const token = store.state.user.token
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
  }

  return config
}, (err) => {
  return Promise.reject(err) // 将err转换为Promise对象
})

// 每次返回数据的拦截
instance.interceptors.response.use(res => res, async err => {
  if (err.response && err.response.status === 401) {
    const [err2, res] = await to(refreshTokenAPI(store.state.user.refreshToken))
    if (err2) {
      // 清空token
      store.commit('user/setToken', '')
      // 跳转到登录界面
      router.push('/login?returnUrl=' + router.currentRoute.fullPath)
    } else {
      console.log('赋值', store.state.user.refreshToken)
      store.commit('user/setToken', res.data.data.token)

      // 执行未执行的请求
      return instance(err.config)
    }
    return Promise.reject(err)
  }
})

// 返回出去一个封装的网络请求
export default ({ headers, method = 'get', data, params, url }) => {
  const promise = instance({
    headers,
    method,
    data,
    params,
    url
  })
  return to(promise)
}
